package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("拦截到请求:uri{} ", uri);
        //2、判断本次请求是否需要处理
        boolean check = check(uri);
        //3、如果不需要处理，则直接放行
        if (check) {
            log.info("当前请求不需要处理，直接放行, uri={}", uri);
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //4.1、判断员工登录状态，如果已登录，则直接放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            log.info("员工登陆成功，放行");
            long id = Thread.currentThread().getId();//当前线程id
            log.info("filter线程Id:{}", id);
            BaseContext.setCurrentId(empId);//把当前登陆的员工id设置到ThreadLocal中
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            log.info("用户登陆成功，放行");
            BaseContext.setCurrentId(userId);//把当前登陆的员工id设置到ThreadLocal中
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        log.info("未登陆，当前请求uri={}", uri);
        //5、如果未登录则返回未登录结果(返回登陆页面) {"code":0, "msg"："NOTLOGIN"}
        R<Object> notlogin = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(notlogin));

    }

    private boolean check(String uri) {
        //定义不需要处理的url
        String[] noHandleUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
        };
        for (String noHandUrl : noHandleUrls) {
            boolean match = ANT_PATH_MATCHER.match(noHandUrl, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}